<template>
  <div>
    <nav class="nav-btn">
       <div class="operate-btn" @click="signInOrOut">
           <div class="img-div"><img class="img-size" src="../assets/image/sigBtnBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">{{signInOrOutText}}</div> 
       </div>     
        <div class="operate-btn" :class="{'opacity':opacity3}" @click="callOut('0')">
           <div class="img-div"><img class="img-size" src="../assets/image/callBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">内呼</div> 
       </div>
        <div class="operate-btn" :class="{'opacity':opacity4}" @click="callOut('1')">
           <div class="img-div"><img class="img-size" src="../assets/image/callOutBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">呼出</div> 
       </div>
       <div class="operate-btn" :class="{'opacity':opacity5}" @click="callOut('2')">
           <div class="img-div"><img class="img-size" src="../assets/image/hangUpBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">挂断</div> 
       </div>
        <div class="operate-btn" :class="{'opacity':opacity6}" @click="callOut('3')">
           <div class="img-div"><img class="img-size" src="../assets/image/scoreBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">满意度</div> 
       </div>
       <div class="operate-btn" :class="{'opacity':opacity7}" @click="callOut('4')">
           <div class="img-div"><img class="img-size" src="../assets/image/keepBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">保持</div> 
       </div>
        <div class="operate-btn" :class="{'opacity':opacity8}" @click="callOut('5')">
           <div class="img-div"><img class="img-size" src="../assets/image/startBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;">解除保持</div> 
       </div>
       <div class="operate-btn" :class="{'opacity':opacity9}">
           <div class="img-div"><img class="img-size" src="../assets/image/transferBlue.png"/></div>
           <div class="easyui-menubutton" style="color: #515a6e;font-size: 14px;">
                <Dropdown trigger="click" @on-click="transfer">
                    <a href="javascript:void(0)" style="color:#000">转接<Icon type="ios-arrow-down"></Icon></a>
                    <DropdownMenu slot="list">
                        <DropdownItem name="agent">转接座席</DropdownItem>
                        <DropdownItem name="queue">转接技能组</DropdownItem>
                        <DropdownItem name="ivr">转接IVR</DropdownItem>
                        <DropdownItem name="pstn">转接外线</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
           </div> 
       </div>
       <div class="operate-btn" :class="{'opacity':opacity10}">
           <div class="img-div"><img class="img-size" src="../assets/image/enquireBlue.png"/></div>
           <div class="easyui-menubutton" id="threeway" style="color: #515a6e;font-size: 14px;">
                <Dropdown trigger="click" @on-click="transfer">
                    <a href="javascript:void(0)" style="color:#000">询问<Icon type="ios-arrow-down"></Icon></a>
                    <DropdownMenu slot="list">
                        <DropdownItem name="askAgent">询问座席</DropdownItem>
                        <DropdownItem name="askPstn">询问外线</DropdownItem>
                        <DropdownItem name="askTransfer">确定询问</DropdownItem>
                        <DropdownItem name="cancelAsk">取消询问</DropdownItem>
                    </DropdownMenu>
                </Dropdown>
           </div> 
       </div>
       <div class="operate-btn" :class="{'opacity':opacity11}" @click="callOut('8')">
           <div class="img-div"><img class="img-size" src="../assets/image/manyBlue.png"/></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;" menu="#setThreeway">多方</div> 
       </div>
       <div class="operate-btn" v-if="minitorMenu &&　minitorMenu.indexOf('7_2-3') > -1" :class="{'opacity':opacity12}" @click="skillMonitor()">
           <div class="img-div"></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;" menu="#setThreeway">技能组监控</div> 
       </div>
       <div class="operate-btn" v-if="minitorMenu && minitorMenu.indexOf('7_2-4') > -1" :class="{'opacity':opacity13}" @click="agentMonitor()">
           <div class="img-div"></div>
           <div class="easyui-linkbutton" style="color: #515a6e;font-size: 14px;" menu="#setThreeway">座席监控</div> 
       </div>
       <div class="operate-btn right-btn status-btn" style="border: none;">
          <Select v-model="agentStatus" class="status-select" :disabled="disabled" style="width:100px" @on-change="handleStatus" @on-open-change="openStatus">
              <Option v-for="(item,index) in agentStatusList" :value="item.id" :key="index">{{ item.name}}</Option>
          </Select>
          <span style="cursor: default;">{{hour<10?"0"+hour:hour}}:{{minute<10?"0"+minute:minute}}:{{second<10?"0"+second:second}}</span>
       </div>
       <div class="operate-btn right-btn">
          <div class="easyui-menubutton" style="color: #515a6e;font-size: 14px;" menu="#showAgentInfo"><span id="agentNumTitle"></span></div> 
       </div>
       
       <Dropdown class="operate-btn right-btn" @on-click="setting" v-if="agentNo" style="margin-left:10px;">
            <a href="javascript:void(0)">{{agentNo}}
                <Icon type="ios-arrow-down"></Icon>
            </a>
            <DropdownMenu slot="list">
                <DropdownItem name="1">员工工号:{{agentNo}}</DropdownItem>
                <DropdownItem name="2">员工分机:{{agentExten ? agentExten.slice(-4) : ''}}</DropdownItem>
                <DropdownItem name="0">个人设置</DropdownItem>
                <DropdownItem name="3">安全退出</DropdownItem>
            </DropdownMenu>
        </Dropdown>
        <div class="operate-btn right-btn" @click="setting('0')">
          <span class="img-head"><img style="height: 35px;width: 35px" src="../assets/image/customerService.png"/></span>
       </div>
       <div class="operate-btn right-btn" style="max-width:200px">
		技能组:<Select style="height:100%;display: inline;max-width: 125px;" v-model="skillgroup" placeholder="请选择技能组" :title="skillgroup" @on-change="skillchange">
                    <Option v-for="(item, index) in SkillList" :value="item.queueNum" :title="item.name" :key="index" >{{item.name}}</Option>
                </Select>
                <p style="width:75px;font-size:15px;height:50%;display: flex;float: left;align-items: center;justify-content: center;">
                <!-- <span style="font-weight:bold">:</span> -->
              <span style="color:red">{{queuelength}}</span>
              <span style="font-size:12px">人排队</span>
            </p>
	   </div>
    </nav>
    <dialer :showDialer="showDialer" @closeDialerPage="closeDialerPage" @dtmfEvent="dtmfEvent" :agentList="agentList" :callType="callType"></dialer>
    <transferPage :showTransferPage="showTransferPage" @closeTransferPage="closeTransferPage" :transferType="transferType" :dataList="dataList"></transferPage>
    <multipartyPop :showMultiparty="showMultiparty" @closeMultiparty="closeMultiparty" :meetingroomList="meetingroomList"></multipartyPop>
    <videoAndAiPage ref="videoComponent"/>
    
    <el-drawer title="来电通知" :visible.sync="showIncoming" :show-close="false" direction="btt" class="answer_cancel" :modal="false" :wrapperClosable="false" :style="maskHeight">
        <el-button type="success" style="margin-top: 20px;margin-left: 15px;" icon="el-icon-phone-outline" @click="answerOrCancel(true)">接听</el-button>
        <el-button type="danger" icon="el-icon-phone" @click="answerOrCancel(false)" style="margin-left: 29px;">挂断</el-button>
    </el-drawer>
    <Modal v-model="showLogin" title="登录界面" sticky reset-drag-position scrollable class="message_template_pop Internal_call" width="500">
      <div v-show="agentInfo && '0' == agentInfo.employeeType && pstnNumberList.length>0" style="margin-bottom:10px;display: flex;" >
        <div style="background-color:#dae2fb;padding:7px 20px 0px 20px;height:32px;width:30%;"><p style="color:#687084;">热线号码:</p></div>
        <Select v-model="pstnNumber" clearable placeholder="请选择热线号码" style="width:70%;margin-right:15px">
          <Option v-for="(item,index) in pstnNumberList" :value="item.pstnNumber" :key="index">{{ item.pstnNumber}}</Option>
        </Select>
      </div>
      <div style="margin-bottom:10px;display: flex;" >
        <div style="background-color:#dae2fb;padding:7px 20px 0px 20px;height:32px;width:30%;"><p style="color:#687084;">座席号码:</p></div>
        <Input placeholder="请输入座席分机" v-model="agentNo" autocomplete="off" style="width:70%;margin-right:15px"/>
      </div>
      <div style="margin-bottom:10px;display: flex;" >
        <div style="background-color:#dae2fb;padding:7px 20px 0px 20px;height:32px;width:30%;"><p style="color:#687084;">座席密码:</p></div>
        <Input placeholder="请输入座席密码" type="password" v-model="agentPassword" autocomplete="off" style="width:70%;margin-right:15px"/>
      </div>
      <div class="btn_style" v-if="loginCount" style="margin-top: 10px;display:flex;align-items: center;">
          <div style="background-color:#dae2fb;padding:7px 20px 0px 20px;height:32px;width:30%;"><p style="color:#687084;">验证码:</p></div>
          <Input v-model="identifyingCode" placeholder="请输右侧验证码"  style="width: 190px"/>
          <identify :createCode="createCode" @changeValidateCode="getValidateCode" style="margin-left: 10px;"></identify>
       </div>
      <template slot="footer">
        <!-- 对于具有验证，点击提交不能消失的对话框，必须使用这种插槽的用法 -->
        <Button type="text" @click="loginCancel">取消</Button>
        <Button type="primary" @click="loginSure" :loading="loading">登录</Button>
      </template>
    </Modal>
    <Modal v-model="showSetExtension" title="设置分机" width='350px' footer-hide :mask-closable='false'>
      坐席分机：
      <el-select v-model="extension" filterable placeholder="请选择分机" style="margin-bottom: 15px;">
        <el-option
          v-for="item in ExtensionList"
          :key="item.agentExten"
          :label="item.agentExten"
          :value="item.agentExten">
        </el-option>
      </el-select>
      <br/>
      <Button type="primary" class="submit_btn" @click="SetExtension()" style="margin-left: 20%;">确认</Button>
      <Button type="error"   class="cancel_btn" @click="showSetExtension=false" style="margin-left: 20%;">取消</Button>
    </Modal>
    <div style="position: fixed; bottom: 0px; font-size: 1px; color: #c6c6c6;">版本标识：U2FsdGVkX188UbR9IOJKylf9ffw+0PcSIbB4/p0MThG1cygxE0ogjoq4K64yAjJz</div>
  </div>  
  
</template>

<script>
import * as CtiClient from '../assets/js/ctiClient.js';

import dialer from './Dialer.vue';
import transferPage from './TransferPage.vue';
import multipartyPop from './MultipartyPop.vue';
import videoAndAiPage from './VideoAndAiPage.vue';
import identify from './Identify.vue';

export default {
  name: 'MainPage',
  components:{
    dialer,
    transferPage,
    multipartyPop,
    videoAndAiPage,
    identify,
  },
  data () {
    return {
      divWidth:{'width': '','overflow':'hidden','line-height': '40px','maxWidth':''},
      maskHeight: { marginLeft: ''},
      second: 0,
      hour: 0,
      minute: 0,
      timeMount: '',
      opacity1: false,
      opacity3: true,
      opacity4: true,
      opacity5: true,
      opacity6: true,
      opacity7: true,
      opacity8: true,
      opacity9: true,
      opacity10: true,
      opacity11: true,
      opacity12: true,
      opacity13: true,
      signInOrOutText: '签入',
      showDialer: false,
      showTransferPage: false,
      showDrawer: true,
      showIncoming: false,
      agentStatusList: [{
                'id': '-1',
                'name': '离线'
            }, {
                'id': '0',
                'name': '空闲'
            }, {
                'id': '1',
                'name': '振铃'
            }, {
                'id': '2',
                'name': '通话'
            }, {
                'id': '3',
                'name': '保持'
            }, {
                'id': '4',
                'name': '后处理'
            }, {
                'id': '5',
                'name': '被占用'
            }, {
                'id': '6',
                'name': '忙碌'
            }, {
                'id': '7',
                'name': '离开'
            }, {
                'id': '8',
                'name': '仅呼出'
            }],
      agentStatus: '-1',
      historyAgentStatus: '0',
      disabled:true,
      callType:'', //0内呼，1外呼
      transferType:'', //0内呼，1外呼
      agentList:[],
      dataList:[],
      SkillList:[],
      skillgroup:'',
      queuelength:0,
      skillTimerFlag:'',
      createdmeeting:false,
      showMultiparty: false,
      showInvitepage: false,
      meetingroomList:[], //会议室成员列表
      showLogin: false,
      agentNo:'', //座席号码
      agentPassword:'',//座席密码
      loading: false,
      agentId:'', //座席id
      minitorMenu:'', //监控按钮
      openWindowSkill: null, //打开的技能组页面
      openWindowAgent: null, //打开的座席页面
      statusTimeOut:'',  //后处理定时器标识
      identifyingCode:'', //验证码
      createCode: '',
      loginCount: false,
      ExtensionList: [], //分机列表
      showSetExtension: false, //选择分机弹窗
      extension: '', // 选择的分机
      agentExten: '', // 缓存中的分机号
      customerPhoneFlag: false, //是否呼入或呼出电话，只有这些电话有满意度、转接、询问、三方
      unholdFlag: false, // 控制三方中解除保持客服状态栏
      conferenceFlag: false, // 多方被叫振铃状态
      conferenceRingFlag: false,
      pstnNumberList: [],
      pstnNumber: '',
      agentInfo: JSON.parse(localStorage.getItem("agentInfo")),
      count: 0
    }
  },
  methods:{
    loginCancel: function(){
      this.showLogin = false;
    },
    
    loginSure: function(){
      if(!this.agentNo || !this.agentPassword){
          this.$Message.error('请输入座席号码或座席密码');
          return false;
      }
      
      this.loading = true;
      var postUrl = "http://"+paramConfig.WEBRTC_SERVICE;
      if(paramConfig.MQTT_SERVICE.indexOf('wss') != -1){
         postUrl = "https://"+paramConfig.WEBRTC_SERVICE;
      }
       let param = {
         "agentNumber":this.agentNo,
         "companyCode":paramConfig.companyCode,
         "employeePassword": this.agentPassword,
         "code":this.identifyingCode,
      }

      this.doLogin(postUrl, param);
    },

    // 登录
    doLogin: function(postUrl,param){
      // 调用系统登录接口进行校验数据
      var httpRequestOne = new XMLHttpRequest(); 
      httpRequestOne.open('POST', postUrl+'/mpccApi/login/doLogin.json', true); 
      httpRequestOne.setRequestHeader("Content-type", "application/json");
      httpRequestOne.send(JSON.stringify(param)); //发送请求 将json写入send中

        /**
        * 获取数据后的处理程序
        */
      let that = this;
      httpRequestOne.onreadystatechange = function () { //请求后的回调接口，可将请求成功后要执行的程序写在其中
      
      if (httpRequestOne.readyState == 4 && httpRequestOne.status == 200) { //验证请求是否发送成功
          that.loading = false;
          var res = JSON.parse(httpRequestOne.responseText);
          let result=res.flag;
          if (result ==  "000") {
            that.$Message.info(res.msg);
            that.getValidateCode();
            return false
          }

          if(result!="666"){
            that.$Modal.info({
                title:'提示',
                content:res.msg
            });
            that.identifyingCode = '';
            that.getValidateCode();
            return false;
          }
          that.count++;
          localStorage.setItem("agentInfo",JSON.stringify(res.obj.agentInfo));
          localStorage.setItem("employeePassword",that.agentPassword);
          paramConfig.agentno = res.obj.agentInfo.agentNumber;
          paramConfig.password = res.obj.agentInfo.agentPassword;
          paramConfig.exten = res.obj.agentInfo.agentExten;
          paramConfig.token = res.obj.token;
          that.agentId = res.obj.agentInfo.agentId;
          that.agentExten = res.obj.agentInfo.agentExten
          localStorage.setItem("agentno",paramConfig.agentno);
          localStorage.setItem("password",paramConfig.password);
          localStorage.setItem("exten", paramConfig.exten);
          localStorage.setItem("agentId", that.agentId);
          localStorage.setItem("token", res.obj.token);
          that.showLogin = false;
          that.loginCount = false;
          that.$Message.success('登录成功');
          that.agentInfo = JSON.parse(localStorage.getItem("agentInfo"));
          if (that.count <= 1) {
            that.getPstnNumber();
          } else {
            paramConfig.pstnnumber=that.pstnNumber;
          }
        }
        if (httpRequestOne.status != 200) {
          that.loading = false;
          that.$Message.error('登录失败');
        }
      }
    },

    setting: function(type){
      if(type == '0'){
        this.showLogin = true;
        paramConfig.password = localStorage.getItem('password');
        this.agentPassword = localStorage.getItem('employeePassword');
      }else if(type == '3'){
        localStorage.removeItem("agentInfo");
        localStorage.setItem("password",'');
        location.reload();
      }
    },
    signInOrOut:function(){
        if(!paramConfig.agentno || !paramConfig.password){
          paramConfig.agentno = localStorage.getItem('agentno');
          paramConfig.password = localStorage.getItem('password');
          paramConfig.exten = localStorage.getItem('exten');
        }else{
          localStorage.setItem("agentno",paramConfig.agentno);
          localStorage.setItem("password",paramConfig.password);
          localStorage.setItem("exten", paramConfig.exten);
          localStorage.setItem("token", paramConfig.token);
        }
        if(!paramConfig.agentno || !paramConfig.password){
          this.showLogin = true;
          return;
        }
        this.agentExten = localStorage.getItem('exten')
        if (!localStorage.getItem('exten')) {
          this.getExtenList();
          return;
        }
        CtiClient.ctiSignInOrOut(paramConfig);
    },
    getExtenList () {
      this.$http.defaults.headers.Authorization="Bearer "+localStorage.getItem('token');
      let param={
        employeeCode:'',
        employeeName:'',
        agentExten:'',
        pstnNumber:'',
        agentNumber:'',
        employeeDepartment:'',
        agentState:'',
        employeeRole:'',
        pageNum:1,
        pageSize:20,
        journalType:"null",
        menuId:"null",
        supportVideo:'',
        aiAssistant:'',
        supportChat:'',
        employeeType:'',
      };
      var postUrl = "http://"+paramConfig.WEBRTC_SERVICE;
      if(paramConfig.MQTT_SERVICE.indexOf('wss') != -1){
        postUrl = "https://"+paramConfig.WEBRTC_SERVICE;
      }
      this.$http.post(postUrl+"/mpccApi/employee/selectAllEmp.json",param).then((res) => {
        let result=res.data.flag;
        if(result!="666"){
          this.$Modal.info({
              title:'提示',
              content:res.data.msg
          });
          return false;
        }
        let obj=res.data.obj;
        this.ExtensionList=obj.agentExtenList;
        this.showSetExtension = true;
      }).catch((err) => {
        this.$Modal.info({
          title:'提示',
          content: '服务器繁忙'
        });
      })
    },
    SetExtension () {
      if(this.extension == ''){
        this.$Modal.info({
          title: '提示',
          content: '请选择分机'
        });
        return;
      }
      this.agentExten = this.extension;
      paramConfig.exten = this.extension;
      this.showSetExtension = false;
      this.signInOrOut();
    },
    getTime: function () {
            clearTimeout(this.timeMount);
            let second = this.second + 1;
            let minute = this.minute;
            let hour = this.hour;
            if (second >= 60) {
                second = 0;
                minute = minute + 1;
            }
            if (minute >= 60) {
                minute = 0;
                hour = hour + 1;
            }
            this.second = second;
            this.minute = minute;
            this.hour = hour;
            let that = this;
            this.timeMount = setTimeout(() => {
                that.getTime();
            }, 1000);
        },
        transfer: function(){

        },
    setToolbarByStatus: function(state,method){
      this.hour = 0;
      this.minute = 0;
      this.second = 0;
      this.agentStatus = state;
      if(method && (method == 'agent_status_change' || method == 'manual_callout_customer_ring' || method == 'manual_callout_customer_answer')){
        this.agentStatusList = [{'id': '0','name': '空闲'}, {'id': '6','name': '忙碌'}, {'id': '8','name': '仅呼出'}];
          let list = [{'id': '-1','name': '离线'}, {'id': '0','name': '空闲'}, {'id': '1','name': '振铃'},
                      {'id': '2','name': '通话'}, {'id': '3','name': '保持'}, {'id': '4','name': '后处理'}, {'id': '5','name': '被占用'},
                      {'id': '6','name': '忙碌'}, {'id': '7','name': '离开'}, {'id': '8','name': '仅呼出'}, {'id': '9','name': '客户振铃'}
                      ,{'id': '10','name': '客户接通'}];
          if (state != "0" && state != "6" && state != "8") {
              for (let i = 0; i < list.length; i++) {
                  if (state == list[i].id) {
                      this.agentStatusList.push(list[i]);
                  }
              }
          }
      }
      // 通话结束把接听界面隐藏
      if(state != '1' && paramConfig.phoneType != '0'){ //0-外置电话 1-内置 外置电话，页面不显示来电通知
            if(localStorage.getItem('showIncoming') == '1') {
              this.showIncoming = false;
            }
      }
      switch(state){
        
        case '-1'://离线
          this.agentStatusList = [{'id': '-1','name': '离线'}];
          this.signInOrOutText = '签入';
          this.disabled = true;//禁用
          this.setToolbarEnabled(false,false,false,false,false,false,false,false,false,false,false,false);
          if(this.skillTimerFlag){
            clearInterval(this.skillTimerFlag);
          }
          this.minitorMenu = '';
          localStorage.setItem('minitorMenu','');
          break;
        case '0': //空闲
          this.callType = '';
          customerPhoneFlag = false;
          this.disabled = false;
          this.duofanging = false;
          duofanging = false;
          this.signInOrOutText = '签出';
          this.setToolbarEnabled(true,true,true,false,false,false,false,false,false,false,true,true);
          this.minitorMenu = localStorage.getItem('minitorMenu');
          this.$refs.videoComponent.videoInit();
          this.SkillList = JSON.parse(localStorage.getItem('skillGroup'));
          break;
        case '1'://振铃
          if(paramConfig.phoneType != '0'){ //0-外置电话 1-内置 外置电话，页面不显示来电通知
            if(localStorage.getItem('showIncoming') == '1') {
              this.showIncoming = true;
            }
          }
          this.disabled = true;
          this.setToolbarEnabled(false,false,false,false,false,false,false,false,false,false,true,true);
          break;
        case '2': //通话
          //外呼和内呼显示按钮不同
          if(this.callType == '0'){  //内呼
            this.disabled = true;
          }
          if (customerPhoneFlag) {  //是否呼入或呼出电话，只有这些电话有满意度、转接、询问、三方
            if (unholdFlag) {
                this.setToolbarEnabled(true, false, false, true, true, false, false, true, true, false, true,true);
                unholdFlag = false;
                conferenceFlag = false;
            } else {
                this.setToolbarEnabled(true, false, false, true, true, false, true, true, true, true, true,true);
            }
          } else {
            this.setToolbarEnabled(true, false, false, true, true, false, false, false, false, false, true,true);
          }
          break;
        case '3'://保持
          this.disabled = true;
          this.setToolbarEnabled(false,false,false,false,false,true,false,false,false,false,true,true);
          break;
        case '4'://后处理
          customerPhoneFlag = false;
          this.disabled = false;
          this.setToolbarEnabled(true,false,false,false,false,false,false,false,false,false,true,true);

          let afterDoTime = parseInt(localStorage.getItem("afterDoTime"));

          // 后处理时长
          if (afterDoTime > 0) {
              this.statusTimeOut = setTimeout(function () {
			  	        CtiClient.sendMessage('change_status','0');
              }, afterDoTime * 1000);
          }
          break;
        case '5'://被占用
          this.disabled = true;
          this.setToolbarEnabled(false,false,false,false,false,false,false,false,false,false,true,true);
          break;
        case '6'://忙碌
          this.disabled = false;
          this.setToolbarEnabled(true,false,false,false,false,false,false,false,false,false,true,true);
          break;
        case '7'://离开
          this.disabled = false;
          this.setToolbarEnabled(true,false,false,false,false,false,false,false,false,false,true,true);
          break;
        case '8'://仅呼出
          customerPhoneFlag = false;
          this.disabled = false;
          this.setToolbarEnabled(true,true,true,false,false,false,false,false,false,false,true,true);
          break;
        case '9'://客户振铃
          this.setToolbarEnabled(false,false,false,true,true,false,true,true,true,true,true,true);
          break;
        case '10'://客户接通
          // this.setToolbarEnabled(false,false,false,true,true,false,true,true,false,true);
          this.setToolbarEnabled(false,false,false,true,true,false,true,true,true,true,true,true);
          break;
      } 
    },
    setToolbarEnabled: function(allStatusFlag,calloutInternalFlag,calloutExternalFlag,hangUpFlag,holdFlag,unHoldFlag,transferFlag,threewayFlag,evaluateFlag,monitorFlag,skillMonitorFlag,agentMonitorFlag){
      if(allStatusFlag){//状态
  			// isChangeStatus("1");  
  		}else{
  			// isChangeStatus("0");
  		}
      this.opacity3 = !calloutInternalFlag;  //内呼
      this.opacity4 = !calloutExternalFlag;  //外呼
      this.opacity5 = !hangUpFlag;  //挂断
  		this.opacity6 = !evaluateFlag;  //满意度
      this.opacity7 = !holdFlag; //保持
      this.opacity8 = !unHoldFlag; //解除保持
      this.opacity9 = !transferFlag; //转接
      this.opacity10 = !monitorFlag; //询问
      this.opacity11 = !threewayFlag; //三方
      this.opacity12 = !skillMonitorFlag; //座席监控
      this.opacity13 = !agentMonitorFlag; //技能组监控
    },
    callOut: function(type){
      this.callType = type;
      switch(type){
        case '0': //内呼
          CtiClient.sendMessage('get_info_of_agent','');
        case '1': //外呼
          this.showDialer = true;
          break;
        case '2': //挂断
          CtiClient.sendMessage('hangup','');
        break;
        case '3': //满意度
          CtiClient.sendMessage('evaluate','');
        break;
        case '4': //保持
          CtiClient.sendMessage('hold','');
        break;
        case '5'://解除保持
          CtiClient.sendMessage('unhold','');
          break;
        case '7': //询问
          // CtiClient.sendMessage('hangup','');
          break;
        case '8': //多方
          // CtiClient.sendMessage('conf_create','');
          if(this.createdmeeting==false){
              CtiClient.sendMessage('conf_create','')
          }
          this.setToolbarEnabled(true,false,false,true,true, false,false,true,true, false, true, true);
          this.showMultiparty=true;

          break;
      }
    },
    // 关闭内外呼界面回调
    closeDialerPage:function(flag, phoneNumber,type){
      this.showDialer = flag;
      if(flag){
        if(phoneNumber){
          if(type == '1'){ //外呼
            CtiClient.sendMessage('manual_callout',phoneNumber);
          }else if(type == '0'){ //内呼
            CtiClient.sendMessage('internal_call',phoneNumber);
          }
        }
      }
    },
    dtmfEvent(dtmf){
      if(CtiClient){
        if(this.agentStatus == '2' || this.agentStatus == '10'){//接通中才发送dtmf
            CtiClient.sendDtmf(dtmf);
        }
      }
    },
    // 关闭转接界面回调
    closeTransferPage:function(flag,phoneNumber){
      this.showTransferPage = false;
      if(flag){
        if(phoneNumber){
          if(flag == 'agent'){ //转接座席
            CtiClient.sendMessage('blind_transfer',phoneNumber);
          }else if(flag == 'queue'){ //转接技能组
            CtiClient.sendMessage('transfer_queue',phoneNumber);
          }else if(flag == 'ivr'){ //转接IVR
            CtiClient.sendMessage('transfer_ivr',phoneNumber);
          }else if(flag == 'pstn'){ //转接外线
            CtiClient.sendMessage('blind_outbound',phoneNumber);
          }else if(flag == 'askAgent'){ //询问座席
            CtiClient.sendMessage("consult",phoneNumber);
          }else if(flag == 'askPstn'){ //询问外线
            CtiClient.sendMessage("consult_outbound",phoneNumber);
          }
        }
      }
    },
    answerOrCancel: function(type){
      localStorage.setItem('showIncoming', '0');
      if(type){  //接听
        CtiClient.answer();
        this.showIncoming = false;
      }else{
        CtiClient.hangUp();
        this.showIncoming = false;
      }
    },
    handleStatus: function (agentStatus) {
      this.hour = 0
      this.minute = 0
      this.second = 0
      this.getTime();
            if (!agentStatus) {
                this.agentStatus = "-1";
	          }
            if("4" != this.agentStatus){
              clearTimeout(this.statusTimeOut);
            }
            CtiClient.sendMessage('change_status',this.agentStatus)
        },
    openStatus: function (flag) {
            let list = [{
                'id': '-1',
                'name': '离线'
            }, {
                'id': '0',
                'name': '空闲'
            }, {
                'id': '1',
                'name': '振铃'
            }, {
                'id': '2',
                'name': '通话'
            }, {
                'id': '3',
                'name': '保持'
            }, {
                'id': '4',
                'name': '后处理'
            }, {
                'id': '5',
                'name': '被占用'
            }, {
                'id': '6',
                'name': '忙碌'
            }, {
                'id': '7',
                'name': '离开'
            }, {
                'id': '8',
                'name': '仅呼出'
            }];
            this.agentStatusList = [{
                'id': '0',
                'name': '空闲'
            }, {
                'id': '6',
                'name': '忙碌'
            }, {
                'id': '8',
                'name': '仅呼出'
            }];
            if (flag) {
                this.historyAgentStatus = this.agentStatus;
            }
            if (this.historyAgentStatus != "0" && this.historyAgentStatus != "6" && this.historyAgentStatus != "8") {
                for (let i = 0; i < list.length; i++) {
                    if (this.historyAgentStatus == list[i].id) {
                        this.agentStatusList.push(list[i]);
                    }
                }
                if (!this.agentStatus) {
                    this.agentStatus = this.historyAgentStatus;
                }
            }
        },
        // 页面刷新执行签出座席
    refreshPage: function(e){
          if(CtiClient){
            CtiClient.refreshPage();
          }
    },
    // 转接/询问
    transfer: function(name){
      this.transferType = name;
      this.transfer
      switch(name){
        case 'askTransfer':  //确定询问
          CtiClient.sendMessage('consult_transfer');
          break;
        case 'cancelAsk'://取消询问
          CtiClient.sendMessage('consult_cancel');
          break;
        case 'agent'://转接座席
          CtiClient.sendMessage('get_info_of_agent','');
          this.showTransferPage = true;
          break;
        case 'queue'://转接技能组
          CtiClient.sendMessage('get_queue_list','');
          this.showTransferPage = true;
          break;
        case 'ivr'://转接ivr
          CtiClient.sendMessage('get_info_of_ivr','');
          this.showTransferPage = true;
           break;
        case 'pstn'://转接外线
          this.showTransferPage = true;
          break;
        case 'askAgent'://询问座席
          CtiClient.sendMessage('get_info_of_agent','');
          this.showTransferPage = true;
          break;
        case 'askPstn'://询问外线
          this.showTransferPage = true;
          break;
      }
    },
    // 获取座席信息
    getInfo: function(jsonStr){
      if(this.transferType == 'agent' || this.transferType == 'askAgent'){
        this.dataList = jsonStr.agentInfoList;
      }else if(this.transferType == 'queue'){
        let skillList =JSON.parse(localStorage.getItem('skillGroup'));
        this.dataList = skillList;
        // this.dataList = jsonStr.skillList.list.content;
      }else if(this.transferType == 'ivr'){
        this.dataList = jsonStr.ivrList.content;
      }
      if(this.callType == '0'){
        this.agentList = jsonStr.agentInfoList;
      }
    },
    getSkillInfo: function(jsonStr){
      if(jsonStr.customer_status){
          this.queuelength = jsonStr.customer_status.split(',').length;
      }else{
          this.queuelength = 0;
      }
    },
    skillchange: function(event){
      if(this.skillgroup){
          //页面顶部获取
          CtiClient.sendMessage('get_customer_of_queue',this.skillgroup,",'param1':'head'");
      }
    },
    //关闭多方会议管理弹窗
        closeMultiparty:function(type,surenumber){
             if (type == "cancel") {
                this.showMultiparty=false;
                return false;
            }
            if (type == 'endmeeting') { //结束会议
                
                CtiClient.sendMessage('conf_stop','');
                this.showMultiparty=false;
                this.showInvitepage=false;
                this.disabled = false;
                this.setToolbarEnabled(false, false, true, true, true, true, true, true, true, true);
            }
            //邀请参加会议
            if(type == 'invitee'){
               CtiClient.sendMessage('conf_invite',surenumber);
            }
            //静音
            if(type == 'mute'){
                CtiClient.sendMessage('conf_mute',surenumber);
            }

            //取消静音
            if(type == 'unmute'){
                CtiClient.sendMessage('conf_unmute',surenumber);
            }

            //移除
            if(type == 'kickoff'){
              CtiClient.sendMessage('conf_kickoff',surenumber);
            }

        },
  
  
  
    //多方操作
    confOperate: function(method,jsonStr){
      switch(method){
         case 'conf_create_result': //多方创建会议返回
            
          if (jsonStr.retCode != '0') {
            this.$Message.info("创建会议失败，" + reason + "");
            this.showMultiparty=false;
          }else{
            this.meetingroomList=[];
            this.showMultiparty=true;
            this.duofanging=true;
            duofanging=true;
            this.createdmeeting=true;
          }
          break;
        case 'conference_ring'://多方被叫振铃
          break;
        case 'conf_stop_result'://多方发送结束命令
          if ("0" === jsonStr.retCode) {
            this.showMultiparty=false;
            this.showInvitepage=false;
            this.meetingroomList=[];
            this.duofanging=false;
            duofanging=false;
            this.createdmeeting=false;
          }else if ("0" != jsonStr.retCode) {
            this.$Message.info("会议结束失败，" + jsonStr.reason + "");
          }
          break;
        case 'conf_destroy'://多方发送结束命令
            this.showMultiparty=false;
            this.showInvitepage=false;
            this.meetingroomList=[];
            this.duofanging=false;
            duofanging=false;
            this.createdmeeting=false;
          break;
        case 'enter_conf'://多方进入会议
          //判断有无前面已在的人员
              let memberNum=jsonStr.memberNumber;
              let removestatu;
              if(memberNum==this.agentNumber){
                removestatu=false;
              }else{
                removestatu=true;
              }
              for(let i=0;i<this.meetingroomList.length;i++){//1遍历meetingroomList
                  if( memberNum==this.meetingroomList[i].number){
                      this.meetingroomList[i].statu="已接通";
                      this.meetingroomList[i].memberID=jsonStr.memberID;
                      this.meetingroomList[i].silence=true;
                      this.meetingroomList[i].remove=removestatu;
                      this.meetingroomList[i].unmute=false;
                      this.meetingroomList[i].reinvite=false;
                      return;
                    }
              }
              let iscustomerflag=0;
              if( this.meetingroomList.length<=2&&memberNum!=this.agentNumber){
                  iscustomerflag=1;
              }
              let member = {//取参加会议人的memberID
                  "number":jsonStr.memberNumber,//改一下这边放被邀请人号码为membernumber
                  "jointime":0,
                  "statu":"已接通",
                  "memberID":jsonStr.memberID,                    //然后还要放memberid进来 传到表格中的第五行(隐藏)
                  "silence":true,
                  "remove":removestatu,
                  "unmute":false,
                  "reinvite":false,
                  "hour":0,
                  "minute":0,
                  "second":0,
                  "iscustomerflag":iscustomerflag,
              }
              this.meetingroomList.push(member);
              break;
            case 'leave_conf'://多方离开会议
                        this.showMultiparty=false;
                            let member2 = jsonStr.memberNumber;//取离开会议人的工号
                            for(let i=0;i<this.meetingroomList.length;i++){//1遍历meetingroomList
                                if( member2 ==this.meetingroomList[i].number){//在for循环判断,工号相等,修改其对应的值
                                    this.meetingroomList[i].statu="离开会议";
                                    this.meetingroomList[i].jointime=0;
                                    this.meetingroomList[i].hour=0;
                                    this.meetingroomList[i].minute=0;
                                    this.meetingroomList[i].second=0;
                                    this.meetingroomList[i].silence=false;
                                    this.meetingroomList[i].remove=false;
                                    this.meetingroomList[i].unmute=false;
                                    this.meetingroomList[i].reinvite=true;
                                    break;
                                }
                            }

                    
              break;
            case 'conf_invite_result'://多方邀请参加返回
              if ("0" != jsonStr.retCode) {
                            let number = parseInt(jsonStr.reason);         //取邀请人的号码
                            for(let i=0;i<this.meetingroomList.length;i++){
                                if( number==this.meetingroomList[i].number){//在for循环判断,number相等,修改其对应的值,把此号码的状态改为邀请失败 时间为0
                                    if(jsonStr.retCode!="200"){
                                        this.meetingroomList[i].statu="未接通";
                                    }else{
                                        this.meetingroomList[i].statu="离开会议";
                                    }
                                    this.meetingroomList[i].jointime=0;
                                    this.meetingroomList[i].silence=false;
                                    this.meetingroomList[i].remove=false;
                                    this.meetingroomList[i].unmute=false;
                                    this.meetingroomList[i].reinvite=true;//失败了则按钮又变成重新邀请
                                    break;
                                }
                            }

                        }
                        break;
            case 'conf_invitee_hangup'://多方邀请被叫忙或拒接
              let number = jsonStr.memberNumber;         //取邀请人的号码
                            for(let i=0;i<this.meetingroomList.length;i++){
                                if( number==this.meetingroomList[i].number){//在for循环判断,number相等,修改其对应的值,把此号码的状态改为邀请失败 时间为0
                                  if(jsonStr.retCode!="200"){
                                    this.meetingroomList[i].statu="未接通";
                                    }else{
                                      this.meetingroomList[i].statu="离开会议";
                                    }
                                    this.meetingroomList[i].jointime=0;
                                    this.meetingroomList[i].second = 0;
                                    this.meetingroomList[i].hour = 0;
                                    this.meetingroomList[i].minute = 0;
                                    this.meetingroomList[i].silence=false;
                                    this.meetingroomList[i].remove=false;
                                    this.meetingroomList[i].unmute=false;
                                    this.meetingroomList[i].reinvite=true;//失败了则按钮又变成重新邀请
                                    break;
                                }
                            }
            break;
      }
    },
    // 技能组监控打开页面
    skillMonitor: function(){
      openWindowSkill = window.open('/demoVue/skill','_blank');
    },
    agentMonitor: function(){
      openWindowAgent = window.open('/demoVue/seat','_blank');
    },
    createRandom:function (count) {
      this.createCode=count;
    },
    getValidateCode:function(){
      let that = this;
      var postUrl = "http://"+paramConfig.WEBRTC_SERVICE;
      if(paramConfig.MQTT_SERVICE.indexOf('wss') != -1){
         postUrl = "https://"+paramConfig.WEBRTC_SERVICE;
      }
      this.$http.get(postUrl+"/mpccApi/common/validateCode.json?employeeCode="+this.agentNo+"&companyCode="+paramConfig.companyCode).then(function (res) {
        let count = res.data+'';
        that.loginCount = true;
        that.createRandom(count);
      })
    },
    // 获取热线号码
    getPstnNumber() {
      this.$http.defaults.headers.Authorization="Bearer "+localStorage.getItem('token');
      let that = this;
      var postUrl = "http://"+paramConfig.WEBRTC_SERVICE;
      if(paramConfig.MQTT_SERVICE.indexOf('wss') != -1){
         postUrl = "https://"+paramConfig.WEBRTC_SERVICE;
      }
      let param = {
        journalType:"null",
        menuId:"null"
      }
      this.$http.post(postUrl+"/mpccApi/personal/toIndex.json",param).then((res) => {
        let result=res.data.flag;
        if(result!="666"){
          this.$Modal.info({
              title:'提示',
              content:res.data.msg
          });
          return false;
        }
        let obj=res.data.obj;
        that.pstnNumberList=[];
        if(obj.pstnNumber && obj.pstnNumber!="null"){
          let newParamList=obj.pstnNumber.split(",");
          for(let i=0;i<newParamList.length;i++){
            let param={
              pstnNumber:newParamList[i]
            };
            that.pstnNumberList.push(param);
          }
        }
        that.pstnNumber = obj.isPstnNumber;
        paramConfig.pstnnumber=obj.isPstnNumber;
      }).catch((err) => {
        this.$Modal.info({
          title:'提示',
          content: '服务器繁忙'
        });
      })
    }
  },
  created(){
    localStorage.clear();
    let clientWidth = document.documentElement.clientWidth - 280;
    this.maskHeight.marginLeft = clientWidth + 'px';
    this.getTime();
    this.agentNo = localStorage.getItem('agentno');
    this.agentPassword = localStorage.getItem('employeePassword');
  },
  mounted() {
    // 监听页面刷新
    window.addEventListener('beforeunload', e =>this.refreshPage(e))
        // 将vue中的方法赋值给window
    window.setToolbarByStatus = this.setToolbarByStatus;
    window.getInfo = this.getInfo;
    window.getSkillInfo = this.getSkillInfo;
    window.confOperate = this.confOperate;
    window.openWindowSkill = this.openWindowSkill;
    window.openWindowAgent = this.openWindowAgent;
    window.customerPhoneFlag = this.customerPhoneFlag;
    window.unholdFlag = this.unholdFlag;
    window.conferenceFlag = this.conferenceFlag;
    window.conferenceRingFlag = this.conferenceRingFlag;
    window.duofanging = this.duofanging;
    window.skillchange = this.skillchange; //技能组排队人数

    window.initAiContent = this.$refs.videoComponent.initAiContent;
    window.doAgentVideo = this.$refs.videoComponent.doAgentVideo;
  },
  watch:{
    
  },
  beforeDestroy () {
    localStorage.clear();
  },
  destroyed() {
    window.removeEventListener('beforeunload', e =>this.refreshPage(e));
  }
}
</script>

<style scoped>
@import '../assets/style/MainPageStyle.less';
</style>
